package com.xiaoh.dormitoryrepairreportbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoh.dormitoryrepairreportbackend.common.BaseResponse;
import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.common.PageResponse;
import com.xiaoh.dormitoryrepairreportbackend.model.dto.common.UpdateRequest;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.Notification;
import com.xiaoh.dormitoryrepairreportbackend.service.NotificationService;
import com.xiaoh.dormitoryrepairreportbackend.utils.QueryUtils;
import com.xiaoh.dormitoryrepairreportbackend.utils.UserHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

/**
 * 通知接口
 */
@RestController
@RequestMapping("/notification")
@Slf4j
@Tag(name = "通知管理", description = "通知相关接口")
public class NotificationController {

    @Resource
    private NotificationService notificationService;

    /**
     * 获取当前用户的通知列表
     * 使用游标分页保持性能，同时返回完整分页信息
     */
    @PostMapping("/list/page")
    @Operation(summary = "分页获取通知列表", description = "获取当前用户的通知列表，返回完整分页信息（总记录数、总页数等）")
    public BaseResponse<PageResponse<Notification>> listNotificationByPage(@RequestBody NotificationQueryRequest queryRequest) {
        if (queryRequest == null) {
            queryRequest = new NotificationQueryRequest();
        }

        Long currentUserId = UserHolder.getCurrentUserId();

        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recipient_id", currentUserId);

        // 添加查询条件
        QueryUtils.addEqCondition(queryWrapper, "is_read", queryRequest.getIsRead());
        QueryUtils.addEqCondition(queryWrapper, "related_type", queryRequest.getRelatedType());

        // 查询总记录数（不包含分页条件）
        QueryWrapper<Notification> countWrapper = QueryUtils.createCountQueryWrapper(queryWrapper);
        Long total = notificationService.count(countWrapper);

        // 添加游标分页
        QueryUtils.addCursorPagination(queryWrapper, queryRequest.getLastId(), queryRequest.getPageSize());

        // 查询通知列表
        List<Notification> notificationList = notificationService.list(queryWrapper);

        // 获取下一页游标
        Long nextCursor = QueryUtils.getNextCursor(notificationList);

        // 计算当前页码
        Long current = QueryUtils.calculateCurrentPage(queryRequest.getLastId(), queryRequest.getPageSize(), total);

        // 构建分页响应
        PageResponse<Notification> pageResponse = PageResponse.of(notificationList, current, queryRequest.getPageSize().longValue(), total, nextCursor);
        return BaseResponse.success(pageResponse);
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/read")
    @Operation(summary = "标记通知为已读", description = "标记指定通知为已读")
    public BaseResponse<Boolean> markAsRead(@Valid @RequestBody UpdateRequest readRequest) {
        if (readRequest == null || readRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long notificationId = readRequest.getId();
        Long currentUserId = UserHolder.getCurrentUserId();
        
        boolean result = notificationService.markAsRead(notificationId, currentUserId);
        return BaseResponse.success(result);
    }

    /**
     * 标记所有通知为已读
     */
    @PostMapping("/read/all")
    @Operation(summary = "标记所有通知为已读", description = "标记当前用户所有通知为已读")
    public BaseResponse<Boolean> markAllAsRead() {
        Long currentUserId = UserHolder.getCurrentUserId();
        boolean result = notificationService.markAllAsRead(currentUserId);
        return BaseResponse.success(result);
    }

    /**
     * 获取未读通知数量
     */
    @PostMapping("/unread/count")
    @Operation(summary = "获取未读通知数量", description = "获取当前用户未读通知数量")
    public BaseResponse<Long> getUnreadCount() {
        Long currentUserId = UserHolder.getCurrentUserId();
        long count = notificationService.getUnreadCount(currentUserId);
        return BaseResponse.success(count);
    }

    /**
     * 通知查询请求DTO
     * 支持游标分页和页码显示的混合模式
     */
    public static class NotificationQueryRequest {
        private Integer isRead;
        private String relatedType;
        private Integer pageSize = 10;
        private Long current = 1L;
        private Long lastId;

        // getters and setters
        public Integer getIsRead() { return isRead; }
        public void setIsRead(Integer isRead) { this.isRead = isRead; }
        public String getRelatedType() { return relatedType; }
        public void setRelatedType(String relatedType) { this.relatedType = relatedType; }
        public Integer getPageSize() { return pageSize; }
        public void setPageSize(Integer pageSize) { this.pageSize = pageSize; }
        public Long getCurrent() { return current; }
        public void setCurrent(Long current) { this.current = current; }
        public Long getLastId() { return lastId; }
        public void setLastId(Long lastId) { this.lastId = lastId; }
    }
}
